//
//  Board.swift
//  Calculator
//
//  Created by 左忠飞 on 2021/1/16.
//  Copyright © 2021 左忠飞. All rights reserved.
//

import UIKit

protocol BoardButtonInputDelegate {
    func boardButtonClick(content:String)
}

class Board: UIView {
    var delegate:BoardButtonInputDelegate?
    var dataArray = ["0",".","%","=",
                     "1","2","3","+",
                     "4","5","6","-",
                     "7","8","9","*",
                     "AC","Delete","^","/"];
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        installUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func installUI() {
        var frontBtn:FuncButton!
        for index in 0..<20 {
            let btn = FuncButton()
            
            self.addSubview(btn)
            
            btn.snp.makeConstraints { (make) in
                //当按钮为第一列,靠左拜访
                if index % 4 == 0{
                    make.left.equalTo(0)
                }else{
                    make.left.equalTo(frontBtn.snp_right)
                }
                //当按钮第一行时,靠下拜访
                if index / 4 == 0{
                    make.bottom.equalTo(0)
                }else if index%4 == 0{
                    make.bottom.equalTo(frontBtn.snp_top)
                }else{
                    make.bottom.equalTo(frontBtn.snp_bottom)
                }
                make.width.equalTo(btn.superview!.snp_width).multipliedBy(0.25)
                make.height.equalTo(btn.superview!.snp_height).multipliedBy(0.2)
            }
            btn.tag = index + 100
            
            btn.addTarget(self, action:#selector(btnClick(btn:)), for: .touchUpInside)
            
            btn.setTitle(dataArray[index], for: .normal)
            
            //保存上一个按钮
            frontBtn = btn
        }
    }
    
    @objc func btnClick(btn:FuncButton) {
        print(btn.title(for: .normal)!)
        if delegate != nil {
            delegate?.boardButtonClick(content: btn.currentTitle!)
        }
    }
}
